/**
 * @description main.ts 全局注入
 */
import { Session } from "inspector";
import { InjectionKey } from "vue";
import { useStore as baseUseStore, createStore, Store } from "vuex";
import cookie from "cookie_js";

interface TableColumn {
  field: string;
  title: string;
  hidden: boolean;
}

interface State {
  userName: string;
  userInfo: {
    userId: string;
    userName: string;
    loginName: string;
    gender: number;
    idcard: string;
    employeeNumber: string;
    mobile: string;
    email: string;
    locked: number;
    orgId: string;
    orgCode: string;
    orgName: string;
    roleCodes: Array<string>;
    roleNames: string;
  };
  config: {
    //config 版本
    ver: string;
    // 侧边栏展开、收缩状态，没有值的时候使用下面配置的默认值 true
    sidebar: boolean;
  };
  tables: Array<{
    tableName: string,
    columns: Array<TableColumn>;
  }>
  token: string;
}

export const key: InjectionKey<Store<State>> = Symbol();

export const store = createStore({
  state: {
    userName: sessionStorage.getItem("userName") || "测试管理员",
    userInfo: JSON.parse(
      sessionStorage.getItem("userInfo") ||
        `{
            \"userId\": \"\",
            \"userName\": \"\",
            \"loginName\": \"\",
            \"gender\": 1,
            \"idcard\": \"\",
            \"employeeNumber\": \"\",
            \"mobile\": \"\",
            \"email\": \"\",
            \"locked\": 0,
            \"orgId\": \"\",
            \"orgCode\": \"\",
            \"orgName\": \"\",
            \"roleCodes\": [],
            \"roleNames\": \"\"
        }`
    ),
    config: JSON.parse(
      localStorage.getItem("config") ||
        `{
            \"ver\": \"1.0.0\",
            \"sidebar\": true
        }`
    ),
    tables:JSON.parse(
      localStorage.getItem("tables") ||
        `[]`
    ),
    token: "",
  },
  // 调用方式 store.getters.getUserName;
  getters: {
    getUserName: (state) => {
      return state.userName;
    },
    getUserInfo: (state) => {
      return state.userInfo;
    },
    getConfig: (state) => {
      return state.config;
    },
    // getTables:(state, tableName: string) :Array<TableColumn> => {
    //   return state.tables[tableName] || [];
    // },
    getColumns:(state) => (tableName: string) : Array<TableColumn> => {
      // debugger;
      let exist = false;
      let columns = Array<TableColumn>();
      state.tables.forEach((value: {tableName: string, columns: Array<TableColumn>}) => {
        if(value.tableName == tableName){
          exist = true;
          columns = value.columns;
          return;
        }
      });
      //上面 forEach 中的 return 并没有终止，下面的 return 还会执行一次
      return columns;
    },
  },
  mutations: {
    SET_USERNAME(state, userName: string) {
      state.userName = userName;
      sessionStorage.setItem("userName", userName);
    },
    SET_USERINFO(state, userInfo: any) {
      // console.log("SET_USERINF");
      state.userInfo = userInfo;
      sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
    },
    SET_CLEAR_SESSION(state) {
      // 注销
      state.userName = "";
      // 不能设置为 null，因为下级属性被其他对象使用，上级对象为 null，即 null.xxx 会引发异常；设置为 {} 会触发响应事件
      state.userInfo = {};
      sessionStorage.removeItem("userName");
      sessionStorage.removeItem("userInfo");
      cookie.remove("token");
    },
    SET_CONFIG(state, config: any) {
      state.config = config;
      localStorage.setItem("config", JSON.stringify(config));
    },
    SET_TOKEN(state, token: string) {
      cookie.set("token", token);
    },
    SET_TABLE_COLUMN(state, table: {tableName: string, columns: Array<TableColumn>}){
      // debugger;
      let exist = false;
      state.tables.forEach((value: {tableName: string, columns: Array<TableColumn>}) => {
        if(value.tableName == table.tableName){
          value.columns = table.columns
          exist = true;
        }
      });
      // console.log("SET_TABLE_COLUMN", state.tables)
      if(!exist){
        state.tables.push(table);
      }
      localStorage.setItem("tables", JSON.stringify(state.tables));
    }
  },
  actions: {},
});

export function useStore() {
  return baseUseStore(key);
}
